package BaseService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"time"
)

func Delete(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := g.Map{
		"delete_at": time.Now().Unix(),
	}
	// 编辑前方法
	if req.DeleteBeforeFn != nil {
		respRes := req.DeleteBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	_, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where(
		"id",
		gconv.SliceAny(req.Ids),
	).Update(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 删除成功，尝试删除缓存
	if g.Cfg().GetBool("site.BaseCacheIsOpen") {
		tools.ClaerCacheByKeyPrefix("backCache:" + req.TableName + ":*")
	}
	result := g.Map{
		"ids": gconv.SliceAny(req.Ids),
	}
	// 后置方法
	if req.DeleteAfterFn != nil {
		respRes := req.DeleteAfterFn(r, data, result)
		if respRes.Code != 0 {
			return respRes
		}
	}
	return response.SuccessByRequestMessageData(nil, "删除成功", result)
}
